<?php

/**
 * This is the model class for table "content".
 *
 * The followings are the available columns in table 'content':
 * @property integer $id
 * @property string $name
 * @property string $text
 * @property integer $seq_number
 * @property string $icon_file_name
 * @property string $created_by
 * @property string $created_date
 * @property string $modified_by
 * @property string $modified_date
 * @property string $active_start_date
 * @property string $active_end_date
 * @property integer $parent_id
 * @property integer $content_type_id
 * @property integer $application_id
 * @property integer $content_status_id
 *
 * The followings are the available model relations:
 * @property ContentType $contentType
 * @property ContentStatus $contentStatus
 * @property Application $application
 * @property ContentPermission[] $contentPermissions
 * @property Document[] $documents
 * @property File[] $files
 * @property Link[] $links
 */
class Content extends CActiveRecord
{
	const ACTION_DELETE = 0;	
	const STATUS_PENDING = 1;
	const STATUS_APPROVED = 2;
	const STATUS_REJECTED = 3;
	const STATUS_NEW = 4;
        const STATUS_PROMO = 5;
        
	const ACTION_STATE =6;
	const ACTION_ENCODE = 7;
	const ACTION_VOTES = 8;
	const ACTION_STARS = 9;
	
	const VIDEO_ID = 67;
	
	public static $hiddenFields = array('id','content_id');
	
	private $_states = array(
		'NSW'=>'New South Wales',
		'SA'=>'South Australia',
		'WA'=>'Western Australia',
		'VIC'=>'Victoria',
		'TAS'=>'Tasmania',
		'NT'=>'Nothern Territory',
		'ACT'=>'Australian Capital Territory',
		'QLD'=>'Queensland'
	);
	
	public function behaviors() 
	{
        return array(
            'SoftDeleteBehavior' => array(
                'class' => 'application.components.behaviors.SoftDeleteBehavior',
                'deleteAttribute' => 'deleted', // optional, default is 'deleted_time'
            ),
        );
    }
	
	
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Content the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'content';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('content_type_id, application_id, content_status_id,deleted', 'required'),
			array('seq_number, parent_id, content_type_id, application_id, content_status_id', 'numerical', 'integerOnly'=>true),
			array('name, icon_file_name, created_by, modified_by', 'length', 'max'=>255),
			array('text, created_date, modified_date, active_start_date, active_end_date', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, name, text, seq_number, icon_file_name, created_by, created_date, modified_by, modified_date, active_start_date, active_end_date, parent_id, content_type_id, application_id, content_status_id', 'safe', 'on'=>'search'),
			array('modified_date','default','value'=>new CDbExpression('NOW()'), 'setOnEmpty'=>false,'on'=>'update'),
        	array('created_date,modified_date','default', 'value'=>new CDbExpression('NOW()'), 'setOnEmpty'=>false,'on'=>'insert'),		
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'contentType' => array(self::BELONGS_TO, 'ContentType', 'content_type_id'),
			'contentStatus' => array(self::BELONGS_TO, 'ContentStatus', 'content_status_id'),
			'application' => array(self::BELONGS_TO, 'Application', 'application_id'),
			'contentPermissions' => array(self::HAS_MANY, 'ContentPermission', 'content_id'),
			//'documents' => array(self::HAS_MANY, 'Document', 'content_id'),
			//'files' => array(self::HAS_MANY, 'File', 'content_id'),
			'ContentLink' => array(self::HAS_ONE, 'ContentLink', 'content_id'),
			'ContentDocument' => array(self::HAS_ONE, 'ContentDocument', 'content_id'),
			'contentFiles' => array(self::HAS_ONE, 'ContentFile', 'content_id'),
			'userDetails' => array(self::HAS_ONE, 'UserDetails', 'content_id')
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'name' => 'Name',
			'text' => 'Text',
			'seq_number' => 'Seq Number',
			'icon_file_name' => 'Icon File Name',
			'created_by' => 'Created By',
			'created_date' => 'Created Date',
			'modified_by' => 'Modified By',
			'modified_date' => 'Modified Date',
			'active_start_date' => 'Active Start Date',
			'active_end_date' => 'Active End Date',
			'parent_id' => 'Parent',
			'content_type_id' => 'Content Type',
			'application_id' => 'Application',
			'content_status_id' => 'Content Status',
			
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('name',$this->name,true);
		$criteria->compare('text',$this->text,true);
		$criteria->compare('seq_number',$this->seq_number);
		$criteria->compare('icon_file_name',$this->icon_file_name,true);
		$criteria->compare('created_by',$this->created_by,true);
		$criteria->compare('created_date',$this->created_date,true);
		$criteria->compare('modified_by',$this->modified_by,true);
		$criteria->compare('modified_date',$this->modified_date,true);
		$criteria->compare('active_start_date',$this->active_start_date,true);
		$criteria->compare('active_end_date',$this->active_end_date,true);
		$criteria->compare('parent_id',$this->parent_id);
		$criteria->compare('content_type_id',$this->content_type_id);
		$criteria->compare('application_id',$this->application_id);
		$criteria->compare('content_status_id',$this->content_status_id);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
    public function getHierarchy(){
        $parentId = "NULL";
        if (isset($_GET['root']) && $_GET['root'] !== 'source') {
            $parentId = (int) $_GET['root'];
        }
        $req = Yii::app()->db->createCommand(
            "SELECT m1.id, m1.name AS text, m2.id IS NOT NULL AS hasChildren "
                . "FROM content AS m1 LEFT JOIN content AS m2 ON m1.id=m2.parent_id "
                . "WHERE m1.parent_id <=> $parentId AND m1.deleted <=> 0 "
                . "GROUP BY m1.id ORDER BY m1.name ASC"
        );
        $children = $req->queryAll();

        return $children;
    }

	public function getTopMenuItems()
	{
		$topContents = $this->findAllByAttributes(array('parent_id'=>'0'));
		$topMenuItems = array();
		$i=0;
		foreach ($topContents as $content) 
		{
			switch ($content->name)
			{
				case 'Users':
					$url = array('/user/index');
					break;
				
				case 'Settings':
					$url = array('/cms/settings');
					break;
					
				case 'Video Gallery':
					$url = array('/video');
					break;
					
				default:
					$url = array('/content/edit', 'id' => $content->id);

			}
			array_push($topMenuItems, array('label' => $content->name, 'url' => $url,'submenuOptions'=>$this->getMenuItems($content->id), 'linkOptions' => array( 'class' => 'menulink'.$i ) ));
		$i++;
        }
        //print_r($topMenuItems);
	    return $topMenuItems;		
	}
	
    public function getMenuItems($id = null) 
	{
	    $criteria = new CDbCriteria;
        $criteria->condition = 'parent_id = '.'0';
		$contents = $this->findAll($criteria);
		$menuItems = array();
		foreach ($contents as $content) 
		{
			array_push($menuItems, array('label' => $content->name, 'url' => array('page/view', 'id' => $content->id), 'linkOptions' => array( 'class' => 'menulink' ) ));
		}
	    return $menuItems;
	}
	
	// Strips out the extension and returns the file name (This works with filenames that have "." in them)
	public static function getFileName($fileName)
	{
		return preg_replace('/\.[^.]*$/', '', $fileName);
	}
	
	public function getFullStateName($state)
	{
		return $this->_states[$state];		
	}
	
}